using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using DesktopWidgetApp.Client.ViewModels;
using TaskStatus = DesktopWidgetApp.Client.ViewModels.TaskStatus;
using Priority = DesktopWidgetApp.Client.ViewModels.Priority;

namespace DesktopWidgetApp.Client.Views
{
    /// <summary>
    /// TaskManagerWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TaskManagerWindow : Window, INotifyPropertyChanged
    {
        // 内存中的任务集合（简化版，不连接实际数据库）
        private List<TaskItemViewModel> _allTasks;
        private string _currentUserId = "user-1";
        private TaskStatus _currentFilterStatus = TaskStatus.All;
        private Priority _currentFilterPriority = Priority.All;
        private string _currentSearchText = string.Empty;

        /// <summary>
        /// 构造函数
        /// </summary>
        public TaskManagerWindow()
        {
            InitializeComponent();
            _allTasks = new List<TaskItemViewModel>();

            // 添加事件处理程序
            TaskFilterComboBox.SelectionChanged += TaskFilterComboBox_SelectionChanged;
            PriorityFilterComboBox.SelectionChanged += PriorityFilterComboBox_SelectionChanged;
            SearchTextBox.TextChanged += SearchTextBox_TextChanged;
            AddTaskButton.Click += AddTaskButton_Click;
            DeleteTaskButton.Click += DeleteTaskButton_Click;
            RefreshButton.Click += RefreshButton_Click;
        }

        /// <summary>
        /// 窗口加载事件
        /// </summary>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            LoadSampleTasks(); // 加载示例任务数据
            ApplyFilters();
        }

        /// <summary>
        /// 加载示例任务数据
        /// </summary>
        private void LoadSampleTasks()
        {
            // 创建一些示例任务
            _allTasks = new List<TaskItemViewModel>
            {
                new TaskItemViewModel
                {
                    Id = Guid.NewGuid().ToString(),
                    Title = "完成项目文档",
                    Description = "编写项目的详细文档，包括使用说明和API文档",
                    Status = TaskStatus.InProgress,
                    Priority = Priority.High,
                    DueDate = DateTime.Now.AddDays(2),
                    Tags = new string[] { "文档", "紧急" }
                },
                new TaskItemViewModel
                {
                    Id = Guid.NewGuid().ToString(),
                    Title = "修复登录页面的bug",
                    Description = "解决用户反馈的登录页面加载缓慢问题",
                    Status = TaskStatus.Todo,
                    Priority = Priority.Urgent,
                    DueDate = DateTime.Now.AddDays(1),
                    Tags = new string[] { "Bug", "前端" }
                },
                new TaskItemViewModel
                {
                    Id = Guid.NewGuid().ToString(),
                    Title = "准备周会演示",
                    Description = "准备下周周会的项目进度演示PPT",
                    Status = TaskStatus.Todo,
                    Priority = Priority.Medium,
                    DueDate = DateTime.Now.AddDays(5),
                    Tags = new string[] { "会议", "计划" }
                },
                new TaskItemViewModel
                {
                    Id = Guid.NewGuid().ToString(),
                    Title = "优化数据库查询",
                    Description = "优化产品列表页面的数据库查询性能",
                    Status = TaskStatus.Completed,
                    Priority = Priority.High,
                    DueDate = DateTime.Now.AddDays(-1),
                    Tags = new string[] { "性能", "后端" }
                }
            };
        }

        /// <summary>
        /// 应用筛选器
        /// </summary>
        private void ApplyFilters()
        {
            var filteredTasks = _allTasks.AsEnumerable();

            // 应用状态筛选
            if (_currentFilterStatus != TaskStatus.All)
            {
                filteredTasks = filteredTasks.Where(t => t.Status == _currentFilterStatus);
            }

            // 应用优先级筛选
            if (_currentFilterPriority != Priority.All)
            {
                filteredTasks = filteredTasks.Where(t => t.Priority == _currentFilterPriority);
            }

            // 应用搜索文本
            if (!string.IsNullOrEmpty(_currentSearchText))
            {
                var searchText = _currentSearchText.ToLower();
                filteredTasks = filteredTasks.Where(t => 
                    t.Title.ToLower().Contains(searchText) || 
                    (t.Description != null && t.Description.ToLower().Contains(searchText)) ||
                    (t.Tags != null && t.Tags.Any(tag => tag.ToLower().Contains(searchText)))
                );
            }

            TaskListDataGrid.ItemsSource = filteredTasks.ToList();
        }

        /// <summary>
        /// 任务筛选器选择变化事件
        /// </summary>
        private void TaskFilterComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (TaskFilterComboBox.SelectedIndex == 0) _currentFilterStatus = TaskStatus.All;
            else if (TaskFilterComboBox.SelectedIndex == 1) _currentFilterStatus = TaskStatus.Todo;
            else if (TaskFilterComboBox.SelectedIndex == 2) _currentFilterStatus = TaskStatus.InProgress;
            else if (TaskFilterComboBox.SelectedIndex == 3) _currentFilterStatus = TaskStatus.Completed;
            else if (TaskFilterComboBox.SelectedIndex == 4) _currentFilterStatus = TaskStatus.Paused;
            else if (TaskFilterComboBox.SelectedIndex == 5) _currentFilterStatus = TaskStatus.Cancelled;

            ApplyFilters();
        }

        /// <summary>
        /// 优先级筛选器选择变化事件
        /// </summary>
        private void PriorityFilterComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PriorityFilterComboBox.SelectedIndex == 0) _currentFilterPriority = Priority.All;
            else if (PriorityFilterComboBox.SelectedIndex == 1) _currentFilterPriority = Priority.Low;
            else if (PriorityFilterComboBox.SelectedIndex == 2) _currentFilterPriority = Priority.Medium;
            else if (PriorityFilterComboBox.SelectedIndex == 3) _currentFilterPriority = Priority.High;
            else if (PriorityFilterComboBox.SelectedIndex == 4) _currentFilterPriority = Priority.Urgent;

            ApplyFilters();
        }

        /// <summary>
        /// 搜索文本变化事件
        /// </summary>
        private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            _currentSearchText = SearchTextBox.Text;
            ApplyFilters();
        }

        /// <summary>
        /// 添加任务按钮点击事件
        /// </summary>
        private void AddTaskButton_Click(object sender, RoutedEventArgs e)
        {
            var taskEditWindow = new TaskEditWindow();
            if (taskEditWindow.ShowDialog() == true)
            {
                try
                {
                    _allTasks.Add(taskEditWindow.TaskItem);
                    ApplyFilters();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("创建任务失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 编辑任务按钮点击事件
        /// </summary>
        private void EditTaskButton_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button == null) return;

            var taskId = button.Tag.ToString();
            var task = _allTasks.FirstOrDefault(t => t.Id == taskId);
            if (task == null) return;

            var taskEditWindow = new TaskEditWindow(task);
            if (taskEditWindow.ShowDialog() == true)
            {
                try
                {
                    // 找到并更新现有任务
                    var index = _allTasks.FindIndex(t => t.Id == taskId);
                    if (index >= 0)
                    {
                        _allTasks[index] = taskEditWindow.TaskItem;
                    }
                    ApplyFilters();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("更新任务失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 删除任务按钮点击事件
        /// </summary>
        private void DeleteTaskButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedTasks = _allTasks.Where(t => t.IsSelected).ToList();
            if (selectedTasks.Count == 0)
            {
                MessageBox.Show("请先选择要删除的任务", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            if (MessageBox.Show($"确定要删除选中的 {selectedTasks.Count} 个任务吗？", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                try
                {
                    foreach (var task in selectedTasks)
                    {
                        _allTasks.Remove(task);
                    }
                    ApplyFilters();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("删除任务失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 刷新按钮点击事件
        /// </summary>
        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            ApplyFilters();
        }

        /// <summary>
        /// 窗口拖动功能
        /// </summary>
        private void Window_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        // INotifyPropertyChanged 实现
        public event PropertyChangedEventHandler? PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}